<?php

namespace app\common\model;

class Model extends \think\Model {
    const STATUS_OK = 1;
    const STATUS_LOCK = 0;

    public static function statusList() {
        return [
            self::STATUS_OK => '正常',
            self::STATUS_LOCK => '锁定',
        ];
    }

    /**
     * 批量更新数据
     * 注意必须有主键才能实现批量更新
     * @param array $data
     * @return int
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     */
    public function batchUpdate(array $data){
        $table = $this->getTable();
        $pk = $this->getPk();
        if(empty($data)){
            throw new \Exception('params data not exist');
        };
        //获取所有的id
        foreach ($data as $item) {
            $keys[] = $item[$pk];
        }
        $col = $this->query("SHOW COLUMNS FROM `{$table}`");
        $cols = [];
        array_map(function($value) use(&$cols){
            $cols[] = $value['Field'];
        },$col);
        //拼接批量更新sql语句
        $sql = "UPDATE {$table} SET ";
        //合成sql语句
        foreach ($data[0] as $key => $value) {
            if(!in_array($key,$cols)) continue;
            if ($key == $pk) continue;
            $sql .= "`{$key}` = CASE `{$pk}` ";
            $i = 0;
            foreach ($data as $k=>$v) {
                $sql .= sprintf("WHEN %d THEN '%s' ", $keys[$i], $v[$key]);
                $i++;
            }
            $sql .= "END, ";
        }
        //把最后一个,去掉
        $sql = substr($sql, 0, strrpos($sql,','));
        //合并所有id
        $ids = implode(',', $keys);
        //拼接sql
        $sql .= " WHERE `{$pk}` IN ({$ids})";
        $res = $this->execute($sql);
        return $res;
    }

    /**
     * thinkPHP 的数据入库更新很不友好，不能判断是否执行成功，
     * 这里做修改
     *
     * 返回值更友好
     * 这个比较坑，不是批量处理
     *
     * @param $dataSet
     * @param bool $replace
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function saveAll2($dataSet, $replace = true ) {
        $db = $this->db(false);
        $db->startTrans();
        try {
            $pk = $this->getPk();

            if (is_string($pk) && $replace) {
                $auto = true;
            }
            foreach ($dataSet as $key => $data) {
                if (!empty($auto) && isset($data[$pk])) {
                    self::update2($data, [], $this->field);
                } else {
                    self::create2($data, $this->field);
                }
            }
            $db->commit();
            return true;
        } catch (\Exception $e) {
            $db->rollback();
            return false;
        }
    }

    /**
     * 写入数据
     * 返回值更友好
     * @access public
     * @param array      $data  数据数组
     * @param array|true $field 允许字段
     * @return false|int
     */
    public static function create2($data = [], $field = null)
    {
        $model = new static();

        if (!empty($field)) {
            $model->allowField($field);
        }
        return $model->isUpdate(false)->save($data, []);
    }

    /**
     * 更新数据
     * 返回值更友好
     * @access public
     * @param array      $data  数据数组
     * @param array      $where 更新条件
     * @param array|true $field 允许字段
     * @return false|int
     */
    public static function update2($data = [], $where = [], $field = null)
    {
        $model = new static();

        if (!empty($field)) {
            $model->allowField($field);
        }

        return $model->isUpdate(true)->save($data, $where);
    }
}